//
//  ZLLCurveView.m
//  test
//
//  Created by Vincent on 2017/4/24.
//  Copyright © 2017年 Vincent. All rights reserved.
//

#import "ZLLCurveView.h"


@implementation ZLLCurveModel

+(ZLLCurveModel *)curveModelWithYvalue:(float)yval yDescription:(NSAttributedString *)yDes{
    
    ZLLCurveModel *model = [ZLLCurveModel new];
    model.yVal = yval;
    model.yDescription = yDes;

    return model;
}

@end




@implementation ZLLCurveComponents

-(ZLLCurveComponents *)init{
    
    self = [super init];
    if(self){
        
        
    }
    return self;
}

-(UIEdgeInsets)edge{
    if(UIEdgeInsetsEqualToEdgeInsets(_edge, UIEdgeInsetsZero)){
        
        _edge = UIEdgeInsetsMake(20, 35, 20, 5);
    }
    
    return _edge;
}

-(NSDictionary *)yDrawOptions{
    
    if(_yDrawOptions==nil){
        _yDrawOptions = @{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:12]};
    }
    
    return _yDrawOptions;
}

-(UIColor *)axisColor{
    if(_axisColor==nil){
        _axisColor = [UIColor blackColor];
    }
    return _axisColor;
}

-(UIColor *)dashColor{
    if(_dashColor==nil){
        _dashColor = [UIColor grayColor];
    }
    return _dashColor;
}

-(int)ySection{
    if(_ySection<=0){
        _ySection = 5;
    }
    return _ySection;
}

-(NSTimeInterval)duration{
    if(_duration<0){
        _duration = 2;
    }
    return _duration;
}

-(float)xDensity{
    if(_xDensity<=0){
        _xDensity = 30;
    }
    return _xDensity;
}



@end




//绘制曲线的容器视图
@interface ZLLCurveBackV : UIScrollView

@property(nonatomic,strong)ZLLCurveComponents *components;

@property(nonatomic,strong)NSArray<NSArray<ZLLCurveModel *> *>*modelArr;

//开始绘制点距离开始的大小(默认是10）
@property(nonatomic,assign)float xBlank;

//每条曲线的颜色
@property(nonatomic,strong)NSArray<UIColor *> *curveColors;

//曲线视图的宽度
@property(nonatomic,assign)CGFloat curveWidth;

//y坐标最大值
@property(nonatomic,assign)CGFloat maxY;

//刻度线高度
@property(nonatomic,assign)CGFloat gridH;

//x轴坐标文字描述
@property(nonatomic,strong)NSArray<NSAttributedString *> *xdestriptions;

@property(nonatomic,assign)int jmpXdes;

//容器图层
@property(nonatomic,strong)CAShapeLayer *backLayer;


-(void)drawBackViewCurve;


@end

@implementation ZLLCurveBackV

-(CAShapeLayer *)backLayer{
    if(_backLayer==nil){
        _backLayer = [CAShapeLayer layer];
        
        [self.layer addSublayer:_backLayer];
    }
    
    return _backLayer;
}

-(float)xBlank{
    if(_xBlank<=0){
        _xBlank = 10;
    }
    return _xBlank;
}

-(void)drawBackViewCurve{
    
    self.backLayer.bounds = CGRectMake(0, 0,self.contentSize.width,self.bounds.size.height);
    self.backLayer.position = CGPointMake(MAX(self.bounds.size.width, self.contentSize.width)/2, self.bounds.size.height/2);
    self.backLayer.backgroundColor = [UIColor clearColor].CGColor;
    
    UIBezierPath *dashPath = [UIBezierPath bezierPath];
    //绘制y坐标刻度线
    for(int i=0;i<self.components.ySection+1;i++){
        
        CGPoint point = CGPointMake(0,self.components.edge.top+i*self.gridH);
        [dashPath moveToPoint:point];
        [dashPath addLineToPoint:CGPointMake(self.backLayer.bounds.size.width-self.components.edge.right, point.y)];
    }
    self.backLayer.fillColor = [UIColor clearColor].CGColor;
    self.backLayer.lineDashPattern = @[@10,@10];
    self.backLayer.strokeColor = self.components.dashColor.CGColor;
    self.backLayer.lineWidth = 1;
    self.backLayer.path = dashPath.CGPath;
    
    
    //绘制曲线图层
    NSMutableArray *sublayers = [NSMutableArray arrayWithArray:self.backLayer.sublayers];
    
    for(CALayer *tmlayer in sublayers){
        [tmlayer removeFromSuperlayer];
    }
    
    for(int i=0;i<self.modelArr.count;i++){
        
        NSArray *tmarr = self.modelArr[i];
        
        CAShapeLayer *tmlayer = [self curveLayerWithModelArray:tmarr lineWidth:1 lineColor:self.curveColors[i]];
        
        [self.backLayer addSublayer:tmlayer];
    }
    
    //绘制x轴文字描述
    for(int i=0;i<self.xdestriptions.count;i+=self.jmpXdes){
        CGSize size = [self sizeForAttributeString:self.xdestriptions[i] boundingSize:CGSizeMake(self.components.xDensity, self.components.edge.bottom)];
        CGPoint point = CGPointMake(self.xBlank+i*self.components.xDensity,self.backLayer.bounds.size.height-self.components.edge.bottom);
        
        
        CATextLayer *txtLayer = [CATextLayer layer];
        txtLayer.bounds = CGRectMake(0, 0, size.width, size.height);
        txtLayer.position = CGPointMake(point.x, point.y+size.height/2+2);
        txtLayer.string = self.xdestriptions[i];
        
        [self.backLayer addSublayer:txtLayer];
    }
    
}

//绘制曲线图层
-(CAShapeLayer *)curveLayerWithModelArray:(NSArray<ZLLCurveModel *> *)modelArr lineWidth:(CGFloat)lineW lineColor:(UIColor *)lineColor{
    
    CAShapeLayer *curveLay = [CAShapeLayer layer];
    
    
    CGFloat chatH = self.backLayer.bounds.size.height-self.components.edge.top-self.components.edge.bottom;
    
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    for(int i=0;i<modelArr.count;i++){
        ZLLCurveModel *model = modelArr[i];
        
        float rate = model.yVal / self.maxY;
        CGPoint point = CGPointMake(self.xBlank+i*self.components.xDensity, self.components.edge.top+(1-rate)*chatH);
        
        if(i==0){
            [path moveToPoint:point];
        }
        else{
            [path addLineToPoint:point];
        }
        
        CGSize size = [self sizeForAttributeString:model.yDescription boundingSize:CGSizeMake(self.components.xDensity,self.components.edge.top)];
        
        
        //y值描述文字
        CATextLayer *txtLayer = [CATextLayer layer];
        txtLayer.bounds = CGRectMake(0, 0, size.width, size.height);
        txtLayer.position = CGPointMake(point.x, point.y-size.height/2);
        txtLayer.contentsScale = [UIScreen mainScreen].scale;
        txtLayer.string = model.yDescription;
        
        [curveLay addSublayer:txtLayer];
        
    }
    
    curveLay.lineWidth = lineW;
    curveLay.strokeColor = lineColor.CGColor;
    curveLay.fillColor = [UIColor clearColor].CGColor;
    curveLay.backgroundColor = [UIColor clearColor].CGColor;
    curveLay.lineJoin = kCALineJoinRound;
    curveLay.path = path.CGPath;
    
    
    return curveLay;
}


//计算属性字符串尺寸
-(CGSize)sizeForAttributeString:(NSAttributedString *)attstr boundingSize:(CGSize)boundSize{
    
    CGSize size = [attstr boundingRectWithSize:boundSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    
    return size;
}


@end



@interface ZLLCurveView ()

//绘制曲线的容器视图
@property(nonatomic,strong)ZLLCurveBackV *curveV;


@end


@implementation ZLLCurveView

-(ZLLCurveComponents *)components{
    if(_components==nil){
        _components = [ZLLCurveComponents new];
    }
    
    return _components;
}

-(ZLLCurveBackV *)curveV{
    if(_curveV==nil){
        _curveV = [ZLLCurveBackV new];
    }
    return _curveV;
}

-(int)jmpXDes{
    if(_jmpXDes<=0){
        _jmpXDes = 1;
    }
    return _jmpXDes;
}

-(void)drawCurve{
    
    CGFloat curveW = [self fitCurveSizeWidth];
    CGFloat blank = 20;
    
    
    self.curveV.frame = CGRectMake(self.components.edge.left, 0, self.bounds.size.width-self.components.edge.left, self.bounds.size.height);
    self.curveV.contentSize = CGSizeMake(curveW+blank, 0);
    self.curveV.backgroundColor = [UIColor clearColor];
    [self addSubview:self.curveV];
    
    self.curveV.components = self.components;
    self.curveV.modelArr = self.curveArr;
    self.curveV.curveColors = self.curveColors;
    self.curveV.curveWidth = curveW;
    self.curveV.xdestriptions = self.xDescriptions;
    self.curveV.jmpXdes = self.jmpXDes;
    self.curveV.maxY = [self maxYvalue];
    self.curveV.gridH = (self.bounds.size.height-self.components.edge.top-self.components.edge.bottom) / self.components.ySection;
    
    [self setNeedsDisplay];
    
    [self.curveV drawBackViewCurve];
    
}

-(void)drawRect:(CGRect)rect{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    //绘制y坐标轴
    CGContextMoveToPoint(ctx, self.components.edge.left, 5);
    CGContextAddLineToPoint(ctx, self.components.edge.left,self.bounds.size.height-self.components.edge.bottom);
    CGContextSetFillColorWithColor(ctx, [UIColor clearColor].CGColor);
    CGContextSetStrokeColorWithColor(ctx, self.components.axisColor.CGColor);
    CGContextSetLineWidth(ctx, 1);
    CGContextStrokePath(ctx);
    
    //绘制y坐标描述文字
    float max = [self maxYvalue];
    float gridH = (self.bounds.size.height-self.components.edge.top-self.components.edge.bottom) / self.components.ySection;
    
    //绘制y刻度描述文字
    float yGrid = max / self.components.ySection;
    for(int i=0;i<self.components.ySection+1;i++){
        NSAttributedString *att = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.1f",max-i*yGrid] attributes:self.components.yDrawOptions];
        
        CGSize size = [self sizeForAttributeString:att boundingSize:CGSizeMake(self.components.edge.left, yGrid)];
        
        CGPoint point = CGPointMake(self.components.edge.left,self.components.edge.top+i*gridH);
        [att drawInRect:CGRectMake(self.components.edge.left-size.width-2, point.y-size.height/2, size.width, size.height)];
    }
    
}

//通过数据模型数组获取最大的y值
-(float)maxYvalue{
    float max = 0;
    for(NSArray *tmarr in self.curveArr){
        for(ZLLCurveModel *model in tmarr){
            if(model.yVal>max){
                max = model.yVal;
            }
        }
    }
    return max;
}


//计算属性字符串尺寸
-(CGSize)sizeForAttributeString:(NSAttributedString *)attstr boundingSize:(CGSize)boundSize{
    
    CGSize size = [attstr boundingRectWithSize:boundSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    
    return size;
}


//绘制曲线视图的宽度
-(CGFloat)fitCurveSizeWidth{
    
    //寻找曲线点数最多的
    int count = 0;
    for(NSArray *tmarr in self.curveArr){
        if(tmarr.count>count){
            count = (int)tmarr.count;
        }
    }
    
    CGFloat width = self.bounds.size.width;
    if(count-1>0){
        CGFloat tmw = (count-1)*self.components.xDensity+self.components.edge.right;
        if(tmw>width){
            width = tmw;
        }
    }

    return width;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
